package cn.tedu.filter;

import cn.tedu.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    //过滤器类型：pre,post,routing,error
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //过滤器插入的位置
    //在第5个过滤器中在上下文对象添加了serviceId，
    //在后面过滤器中才能访问 serviceId
    @Override
    public int filterOrder() {
        return 6;
    }

    //对用户请求进行判断，是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /**
         * 只对item-service调用进行过滤
         * 如果调用user-service或order-service不执行过滤代码
         */
        //获得调用的服务id
        RequestContext rcx = RequestContext.getCurrentContext();
        String serviceId = (String) rcx.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {

        //获得request对象
        RequestContext rct = RequestContext.getCurrentContext();
        HttpServletRequest request = rct.getRequest();

        //接收token对象
        String token = request.getParameter("token");

        //如果没有token，阻止访问，并直接向客户端返回响应
        if(StringUtils.isBlank(token)){
            //阻止继续访问
            rct.setSendZuulResponse(false);
            //JsonResult {code:401,msg:not login,data:null}
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN)
                    .msg("not login")
                    .data("null")
                    .toString();
            rct.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            rct.setResponseBody(json);
        }
        return null;
    }
}
